﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Data;
using System.Collections;
using System.Web.UI.WebControls;
using System.Text;
using System.Web.UI;
using Etong.Web;
/// <summary>
/// 用于与xml配置文件交互的实体类,对应数据库中的表
/// </summary>
[Serializable]
public class ConfigTable
{
	public ConfigTable()
	{
        this.AllowAdd = true;
        this.AllowEdit = true;
        this.AllowDel = true;
        this.PkFiledName = "id";
        this.AllowPageing = true;
        this.PageSize = 10;
        this.ParentRootValue = "0";
        this.ChildDepth = 0;
        this.AllowMultiSelect = true;
        this.AllowOutput = false;
	}

    public ConfigTable(string tableName):this()
    {
        this.TableName = tableName;        

        if (this.list == null)
        {
            this.list = new List<ConfigColumns>();
        }

        DataView columnsTab = (DataView)DBFactory.GetSchema().GetColumnsInTable(this.TableName);
        foreach (DataRow row in columnsTab.Table.Rows)
        {
            list.Add(new ConfigColumns(row["column_name"].ToString(),row["data_type"].ToString(),this.TableName));
        }
    }

    public ConfigTable(string tablename, string xmlname)
        : this(tablename)
    {
        this.XmlName = xmlname;
        this.ListUrl = "list.aspx?tab=" + this.TableName+"&xml="+xmlname;
        this.EditUrl = "edit.aspx?type=edit&tab=" + this.TableName + "&xml="+xmlname+"&id={0}";
        this.EditUrlParameters = new string[] { "id" };
        this.AddUrl = "edit.aspx?type=add&tab=" + this.TableName + "&xml="+xmlname+"&typeid={0}";
        this.AddUrlParameters = new string[] { "typeid" };
        this.DeleteUrl = "del.ashx?tab=" + this.TableName + "&xml="+xmlname+"&id={0}";
        this.DeleteUrlParameters = new string[] { "id" };
        this.ShowUrl = "show.aspx?tab=" + this.TableName + "&xml="+xmlname+"&id={0}";
        this.ShowUrlParameters = new string[] { "id" };
    }
    public bool AllowOutput { get; set; }
    public string BeforeInsertClassName { get; set; }
    public string BeforeUpdateClassName { get; set; }
    public string BeforeDeleteClassName { get; set; }

    public string AfterInsertClassName { get; set; }
    public string AfterUpdateClassName { get; set; }
    public string AfterDeleteClassName { get; set; }

    public string TableName { get; set; }
    public string TableShowName { get; set; }
    public string LocationText { get; set; }
    public string XmlName { get; set; }
    public string PkFiledName { get; set; }
        
    public string ParentColumnName { get; set; }
    public string ParentRootValue { get; set; }
    public int ChildDepth { get; set; }

    public bool AllowPageing { get; set; }
    public int PageSize { get; set; }

    public bool AllowMove { get; set; }
    public string TypeTableParamName { get; set; }

    public string FkFiledName { get; set; }
    public string FkMainTableName { get; set; }

    public string OrderFieldName { get; set; }
    public string OrderSql { get; set; }
    public string OrderGroupColumnName { get; set; }

    public bool AllowAdd { get; set; }
    public bool AllowEdit { get; set; }
    public bool AllowDel { get; set; }
    public bool AllowShow { get; set; }
    public bool SingleType { get; set; }
    public bool AllowMultiSelect { get; set; }

    public bool AllowRolebrowseContrl { get; set; }
    public bool AllowUserBrowseContrl { get; set; }
    public string[] AllowRoles { get; set; }
    public string[] AllowUsers { get; set; }

    public string ListUrl { get; set; }
    public string[] ListUrlParameters { get; set; }
    public string ListViewName { get; set; }
    public string ListViewXmlName { get; set; }

    public string AddUrl { get; set; }
    public string[] AddUrlParameters { get; set; }

    public string EditUrl { get; set; }
    public string[] EditUrlParameters { get; set; }

    public string DeleteUrl { get; set; }
    public string[] DeleteUrlParameters { get; set; }

    public string ShowUrl { get; set; }
    public string[] ShowUrlParameters { get; set; }

    private List<ConfigColumns> list = new List<ConfigColumns>();
    public List<ConfigColumns> Columns 
    {
        get
        {
            return list;
        }
        set
        {
            list = value;
        }
    }

    public ConfigColumns this[string ColumnName]
    {
        get 
        {
            foreach (ConfigColumns c in this.Columns)
            {
                if (c.ColumnName.ToLower().Trim() == ColumnName.ToLower().Trim())
                {
                    return c;
                }
            }
            return null;
        }
    }


    public static ConfigTable GetDefaultConfig(string TableName)
    {
        string path = HttpContext.Current.Server.MapPath("~/configs/tables/" + TableName + "/");
        DirectoryInfo dir = new DirectoryInfo(path);
        return dir.GetFiles().First().FullName.XmlToObj<ConfigTable>();
    }

    public string GetLocationText()
    {
        string location = this.TableShowName;

        string listType = HttpContext.Current.Request.QueryString["lt"];
        string listValue = HttpContext.Current.Request.QueryString["lv"];

        if (!string.IsNullOrEmpty(listValue))
        {
            location += GetChildLocationText(listValue);
        }

        return location;
    }

    private string GetChildLocationText(string lv)
    {
        ConfigTable fTab= ConfigTable.GetDefaultConfig(this.FkMainTableName);
        string r = ">>";
        string sql = "select * from " + this.FkMainTableName + " where " + fTab.PkFiledName + "=" + DataTypeFactory.GetSqlValue(lv, fTab[fTab.PkFiledName].ColumnDataType);
        DataRow row = DBFactory.GetConn().exeRow(sql);
        if (row != null)
        {
            string thisR = row[fTab.LocationText].ToString();
            r += thisR;
            if (!string.IsNullOrEmpty(fTab.ParentColumnName))
            {
                string thisP = row[fTab.ParentColumnName].ToString();

                if (thisP != fTab.ParentRootValue)
                {
                    r = GetChildLocationText(thisP) + r;
                }
            }
        }

        return r;
    }

    public void SetupListGridFields(GridView grid)
    {
        if (!string.IsNullOrEmpty(this.ListViewName) && !string.IsNullOrEmpty(this.ListViewXmlName))
        {            
            ConfigTable cTab = ConfigTable.GetConfigTable(this.ListViewName, ListViewXmlName);            
            cTab.SetupListGridFields(grid);
            return;
        }
        grid.Columns.Clear();
        if (this.AllowMultiSelect)
        {
            TemplateField multiCheck = new TemplateField();
            Page page = HttpContext.Current.Handler as Page;
            string basepath = ConfigGlobal.GetGlobal().AdminDir;
            multiCheck.HeaderTemplate = page.LoadTemplate(basepath + "ascx/MulticheckTemplateHeader.ascx");
            multiCheck.ItemTemplate = page.LoadTemplate(basepath + "ascx/MultiCheckTemplate.ascx");            
            //multiCheck.HeaderStyle.Width = new Unit(40);
            //multiCheck.ItemStyle.Width = new Unit(40);
            multiCheck.ItemStyle.CssClass = "multiCheckItem";
            multiCheck.HeaderStyle.CssClass = "multiCheckHeader";
            multiCheck.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            grid.Columns.Add(multiCheck);
        }
        if (!string.IsNullOrEmpty(this.ListViewName) && !string.IsNullOrEmpty(this.ListViewXmlName))
        {
            string viewPath = HttpContext.Current.Server.MapPath("~/configs/tables/" + this.ListViewName + "/" + this.ListViewXmlName + ".xml");
            ConfigTable cTab = viewPath.XmlToObj<ConfigTable>();
            cTab.SetupListGridFields(grid);
            return;
        }
        var ListShowColumns = this.Columns.Where(x => x.IsListShow).OrderBy(y => y.ListShowOrder);
        foreach (var col in ListShowColumns)
        {
            DataControlField field = ListShowFactory.GetListColumnTypeClass(col.ListShowType).GetListField(col);
            if (col.ListShowAllowSort)
            {
                field.SortExpression = col.ColumnName;
            }
            field.ItemStyle.HorizontalAlign = col.ListHAlign;
            grid.Columns.Add(field);
        }        
        grid.AutoGenerateColumns = false;
        grid.DataKeyNames = this.PkFiledName.Split(',');
    }

    public DataTable GetMenuDataSource(string listSql,string Ordersql)
    {
        string basesql = listSql;
        string sql =basesql  + Ordersql;
        return GetMenuDataSource(sql);
    }

    public DataTable GetMenuDataSource(string sql)
    {
        if (!string.IsNullOrEmpty(this.ParentColumnName))
        {
            sql = sql.Insert(sql.IndexOf("select ") + "select ".Length, " " + this.ParentColumnName + ",");
        }        
        DataTable tab = DBFactory.GetConn().exeTable(sql);

        DataTable newTab = new DataTable();
        newTab.Columns.Add(new DataColumn("lev"));

        foreach (DataColumn c in tab.Columns)
        {
            newTab.Columns.Add(new DataColumn(c.ColumnName));
        }

        //if (!string.IsNullOrEmpty(this.ParentColumnName) && !string.IsNullOrEmpty(this.ParentRootValue))
        {
            SetChildRowsInMenu(tab, newTab, this.ParentRootValue, 0);
        }        

        return newTab;
    }

    private void SetChildRowsInMenu(DataTable sourceTab,DataTable newTab,string pid,int depth)
    {
        var list = from DataRow row in sourceTab.Rows                   
                   select row;
        if (!string.IsNullOrEmpty(this.ParentColumnName))
        {
            list = list.Where(x => x[this.ParentColumnName].ToString() == pid);
        }

        List<DataRow> List = list.ToList<DataRow>();
        foreach (DataRow row in List)
        {
            newTab.Rows.Add(GetRowDataSource(row, depth, List, sourceTab).ToArray());
            if (!string.IsNullOrEmpty(this.ParentColumnName))
            {
                SetChildRowsInMenu(sourceTab, newTab, row[this.PkFiledName].ToString(), depth + 1);
            }
        }
    }

    private List<object> GetRowDataSource(DataRow row, int depth,List<DataRow> List,DataTable tab)
    {
        List<object> p = new List<object>();        
        string temp = depth.ToString();
        //if (row == List[0])
        //{
        //    if (depth == 0)
        //    {
        //        temp = "┌";
        //    }
        //    else
        //    {
        //        temp = "├";
        //    }

        //    if (row == List[List.Count - 1])
        //    {
        //        temp = "└";
        //    }
        //}
        //else if (row == List[List.Count - 1])
        //{
        //    temp = "└";
        //}
        //else
        //{
        //    temp = "├";
        //}
        //if (depth != 0)
        //{
        //    for (int i = 1; i < depth; i++)
        //    {
        //        temp = "│" + temp;
        //    }
        //    temp = "│" + temp;
        //}
        //temp += "+" + depth.ToString();
        p.Add(temp);
        foreach (DataColumn c in tab.Columns)
        {
            string str = row[c.ColumnName].ToString();
            p.Add(str);
        }

        return p;
    }

    public void SetupMenuGridFields(GridView grid)
    {
        grid.Columns.Clear();
        if (this.AllowMultiSelect)
        {
            TemplateField multiCheck = new TemplateField();
            Page page = HttpContext.Current.Handler as Page;
            multiCheck.HeaderTemplate = page.LoadTemplate(ConfigGlobal.GetGlobal().AdminDir + "ascx/MulticheckTemplateHeader.ascx");
            multiCheck.ItemTemplate = page.LoadTemplate(ConfigGlobal.GetGlobal().AdminDir + "ascx/MultiCheckTemplate.ascx");
            grid.Columns.Add(multiCheck);
        }

        BoundField levField = new BoundField();
        levField.DataField = "lev";
        grid.Columns.Add(levField);

        if (!string.IsNullOrEmpty(this.ListViewName) && !string.IsNullOrEmpty(this.ListViewXmlName))
        {
            string viewPath = HttpContext.Current.Server.MapPath("~/configs/tables/" + this.ListViewName + "/" + this.ListViewXmlName + ".xml");
            ConfigTable cTab = viewPath.XmlToObj<ConfigTable>();
            cTab.SetupMenuGridFields(grid);
            return;
        }
        var ListShowColumns = this.Columns.Where(x => x.IsListShow).OrderBy(y => y.ListShowOrder);
        foreach (var col in ListShowColumns)
        {
            DataControlField field = ListShowFactory.GetListColumnTypeClass(col.ListShowType).GetListField(col);
            if (col.ListShowAllowSort)
            {
                field.SortExpression = col.ColumnName;
            }
            field.ItemStyle.HorizontalAlign = col.ListHAlign;
            grid.Columns.Add(field);
        }
        
        grid.AutoGenerateColumns = false;
        grid.DataKeyNames = this.PkFiledName.Split(',');

        grid.DataBound += new EventHandler(grid_DataBound);
        grid.PreRender += new EventHandler(grid_PreRender);
    }

    void grid_PreRender(object sender, EventArgs e)
    {
        GridView grid = sender as GridView;
        if (grid != null)
        {
            grid.UseAccessibleHeader = true;
            try
            {
                grid.HeaderRow.TableSection = TableRowSection.TableHeader;
            }
            catch (Exception ex)
            { }
        }
    }

    void grid_DataBound(object sender, EventArgs e)
    {
        int levIndex = 0;
        if (this.AllowMultiSelect)
        {
            levIndex = 1;
        }

        GridView grid = sender as GridView;
        if (grid != null)
        {
            #region onuse
            //    for (int i = grid.Rows.Count - 1; i > -1; i--)
        //    {
        //        if (grid.Rows[i].RowType == DataControlRowType.DataRow)
        //        {
        //            string txt = grid.Rows[i].Cells[levIndex].Text;
        //            if (txt.StartsWith("│"))
        //            {
        //                txt = txt.Replace("│", "_");
        //                grid.Rows[i].Cells[levIndex].Text = txt;
        //            }
        //            else
        //            {
        //                break;
        //            }
        //        }

            //    }
            #endregion
            //先根据lev设置那些不显示添加子节点
            int colIndex = grid.Columns.Count - 4;
            if (!this.AllowShow) { colIndex++; }
            if (!this.AllowEdit) { colIndex++; }
            if (!this.AllowDel) { colIndex++; }

            foreach (GridViewRow row in grid.Rows)
            {
                if (int.Parse(row.Cells[levIndex].Text) >= this.ChildDepth)
                {
                    row.Cells[colIndex].Text = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                }
            }

            #region nouse
            //foreach (GridViewRow row in grid.Rows)
            //{
            //    if (row.RowType == DataControlRowType.DataRow)
            //    {
            //        string str = row.Cells[levIndex].Text.Split('+')[0];
            //        string newstr = str;

            //        newstr = newstr.Replace("┌", "<img src='images/1.gif' border='0' />");
            //        newstr = newstr.Replace("│", "<img src='images/2.gif' border='0' />");
            //        newstr = newstr.Replace("├", "<img src='images/3.gif' border='0' />");
            //        newstr = newstr.Replace("└", "<img src='images/4.gif' border='0' />");
            //        newstr = newstr.Replace("_", "<img src='images/5.gif' border='0' />");

            //        row.Cells[levIndex + 1].Text = newstr + row.Cells[levIndex + 1].Text;

            //        string thislev = row.Cells[levIndex].Text.Split('+')[1];
            //        int thisLev = 0;
            //        int.TryParse(thislev, out thisLev);
            //        if (this.ChildDepth > 0)
            //        {
            //            if (thisLev >= this.ChildDepth)
            //            {
            //                row.Cells[colIndex].Text = string.Empty;
            //            }
            //        }
            //    }
            //}
            //grid.Columns[levIndex].Visible = false;
            #endregion

            string addchildurl = this.AddUrl.Replace("{0}", "0");
            try
            {
                grid.HeaderRow.Cells[colIndex].Text = "<a href='" + addchildurl + "'>添加节点</a>";
            }
            catch (Exception ex)
            { }

            //再将lev转换为树状信息
            for (int i = 0; i < grid.Rows.Count; i++)
            {
                if (grid.Rows[i].RowType == DataControlRowType.DataRow)
                {
                    string cellText = grid.Rows[i].Cells[levIndex].Text;
                    int cellLev = int.Parse(cellText.Split(',')[0]);
                    if (cellLev != 0)
                    {
                        for (int j = i; j >= 0; j--)
                        {
                            string jcellText = grid.Rows[j].Cells[levIndex].Text;
                            int jcellLev = int.Parse(jcellText.Split(',')[0]);
                            if (jcellLev == cellLev - 1)
                            {
                                grid.Rows[i].Cells[levIndex].Text += "," + (j + 1);
                                break;
                            }
                        }
                    }
                }
            }


            foreach (GridViewRow row in grid.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    string cellText = row.Cells[levIndex].Text;
                    if (cellText.Split(',').Length > 1)
                    {
                        row.Cells[levIndex].Text = cellText.Split(',')[1];
                    }
                }
            }
        }
    }

    public void BindGrid(SqlDataSource source, string BaseSql, string WhereSql, string OrderSql)
    {
        //source.ConnectionString = DBFactory.GetConn().Connection.ConnectionString;
        //source.ProviderName = DBFactory.GetConn().ProviderName;
        //source.SelectCommand = BaseSql + WhereSql + OrderSql;
        BindGrid(source, BaseSql + WhereSql + OrderSql);
    }
    public void BindGrid(SqlDataSource source, string sql)
    {
        source.ConnectionString = DBFactory.GetConn().Connection.ConnectionString;
        source.ProviderName = DBFactory.GetConn().ProviderName;
        source.SelectCommand = sql;
    }

    public string GetListBaseSql()
    {
        if (!string.IsNullOrEmpty(this.ListViewName) && !string.IsNullOrEmpty(this.ListViewXmlName))
        {
            //string viewPath = HttpContext.Current.Server.MapPath("~/configs/tables/" + this.ListViewName + "/" + this.ListViewXmlName + ".xml");
            //ConfigTable cTab = viewPath.XmlToObj<ConfigTable>();
            ConfigTable cTab = ConfigTable.GetConfigTable(this.ListViewName, ListViewXmlName);
            
            return cTab.GetListBaseSql();
        }
        StringBuilder sb = new StringBuilder();
        sb.Append("select ");
        sb.Append(this.PkFiledName);        
        foreach (var col in this.Columns.Where(x => x.IsListShow).OrderBy(y=>y.ListShowOrder))
        {
            sb.Append(",");
            if (col.ListShowType == ListShowType.Foreign)
            {
                sb.Append("(select ");
                sb.Append(col.ListShowForeignTableShowField);
                sb.Append(" from ");
                sb.Append(col.ListShowForeignTable);
                string tempTableName = col.ListShowForeignTable;
                if (col.ListShowForeignTable.ToLower() == this.TableName.ToLower())
                {
                    tempTableName += "_temp";
                }
                sb.Append(" as ");
                sb.Append(tempTableName);
                sb.Append(" where ");
                sb.Append(tempTableName);
                sb.Append(".");
                sb.Append(col.ListShowForeignTablePK);
                sb.Append("=");
                sb.Append(this.TableName);
                sb.Append(".");
                sb.Append(col.ColumnName);
                sb.Append(") as ");
                sb.Append(col.ColumnName);
                sb.Append("_Foreign");                
            }
            else
            {                
                sb.Append(col.ColumnName);
            }
        }        
        sb.Append(" from ");
        sb.Append(this.TableName);
        //sb.Append(" where 1=1");
        return sb.ToString();
    }

    public string GetListOrderSql()
    {
        if (!string.IsNullOrEmpty(this.ListViewName) && !string.IsNullOrEmpty(this.ListViewXmlName))
        {
            //string viewPath = HttpContext.Current.Server.MapPath("~/configs/tables/" + this.ListViewName + "/" + this.ListViewXmlName + ".xml");
            //ConfigTable cTab = viewPath.XmlToObj<ConfigTable>();
            ConfigTable cTab = ConfigTable.GetConfigTable(this.ListViewName, ListViewXmlName);
            
            return cTab.GetListOrderSql();
        }
        string orderSql = " order by " + this.PkFiledName;
        if (!string.IsNullOrEmpty(this.OrderSql))
        {
            orderSql = " order by " + this.OrderSql;
        }        
        return orderSql;
    }

    public string GetListWhereSql(string ListTypeColumnName,string ListTypeValue)
    {
        if (!string.IsNullOrEmpty(this.ListViewName) && !string.IsNullOrEmpty(this.ListViewXmlName))
        {
            //string viewPath = HttpContext.Current.Server.MapPath("~/configs/tables/" + this.ListViewName + "/" + this.ListViewXmlName + ".xml");
            //ConfigTable cTab = viewPath.XmlToObj<ConfigTable>();
            ConfigTable cTab = ConfigTable.GetConfigTable(this.ListViewName, ListViewXmlName);
            
            return cTab.GetListWhereSql(ListTypeColumnName,ListTypeValue);
        }
        StringBuilder whereSql = new StringBuilder();
        if (string.IsNullOrEmpty(ListTypeColumnName) || string.IsNullOrEmpty(ListTypeValue))
        {
            whereSql.Append(" where 1=1");
        }
        else
        {
            bool addTypeSearch = true;
            if ((HttpContext.Current.Handler as Page).IsPostBack)
            {
                if (this.Columns.Count(x => x.IsSearchShow && x.ColumnName.ToLower() == ListTypeColumnName.ToLower()) > 0)
                {
                    if (!string.IsNullOrEmpty(HttpContext.Current.Request[ListTypeColumnName + "_SearchShow"]))
                    {
                        addTypeSearch = false;
                    }
                }
            }
            if (addTypeSearch)
            {
                whereSql.Append(" where ");
                whereSql.Append(ListTypeColumnName);
                whereSql.Append("=");
                whereSql.Append(DataTypeFactory.GetSqlValue(ListTypeValue, this[ListTypeColumnName].ColumnDataType));
            }
            else
            {
                whereSql.Append(" where 1=1");
            }
        }
        var list = this.Columns.Where(x => x.IsSearchShow);
        foreach (var col in list)
        {
            bool addSql = true;
            string value = HttpContext.Current.Request[col.ColumnName + "_SearchShow"];
            if (col.SearchShowRunType == SearchRunType.Between || col.SearchShowRunType== SearchRunType.DateTimeBetween)
            {
                string min = HttpContext.Current.Request[col.ColumnName + "_SearchShow_min"];
                string max = HttpContext.Current.Request[col.ColumnName + "_SearchShow_max"];     
                value = min + "," + max;
                if (value == ",")
                {
                    value = string.Empty;
                }
            }
            if (string.IsNullOrEmpty(value))
            {
                addSql = false;
            }
            if (col.SearchShowRunType == SearchRunType.TemplateRunSql && col.SearchShowType == SearchShowType.Template)
            {
                string[] param = col.SearchShowTemplateValuesFrom.Split(',');
                foreach (string str in param)
                {
                    if (!string.IsNullOrEmpty(HttpContext.Current.Request[col.ColumnName + "_SearchShow$" + str]))
                    {
                        addSql = true;
                    }
                }
            }
            if (addSql)
            {
                whereSql.Append(" and (");
                whereSql.Append(SearchRunFactory.GetSearchRunTypeClass(col.SearchShowRunType).GetSearchString(col, value));
                whereSql.Append(")");
            }            
        }

        return whereSql.ToString();
    }

    public void SetOrderLink(GridView grid)
    {
        if (!string.IsNullOrEmpty(this.OrderFieldName))
        {
            //数据库与配置文件不同步引起的不生效问题
            //if (this[this.OrderFieldName] != null)
            {
                HyperLinkField up = new HyperLinkField();
                up.Text = "<img src='images/up.jpg' border='0' title='向上' alt='向上' />";
                up.DataNavigateUrlFields = new string[] { this.PkFiledName };
                up.DataNavigateUrlFormatString = "OrderGo.ashx?tab=" + this.TableName + "&xml=" + this.XmlName + "&d=up&id={0}";
                up.ItemStyle.Width = new Unit(20);
                HyperLinkField down = new HyperLinkField();
                up.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                down.Text = "<img src='images/down.jpg' border='0' title='向下' alt='向下' />";
                down.DataNavigateUrlFields = new string[] { this.PkFiledName };
                down.DataNavigateUrlFormatString = "OrderGo.ashx?tab=" + this.TableName + "&xml=" + this.XmlName + "&d=down&id={0}";
                down.ItemStyle.Width = new Unit(20);
                down.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                grid.Columns.Add(up);
                grid.Columns.Add(down);
            }
        }
    }

    public static string SetupLink(string url, ref string[] param)
    {
        string[] paramArr = param;
        string newparam = string.Empty;
        string newurl = url;
        for (int i = 0; i < paramArr.Length; i++)
        {
            string[] thisPArr = paramArr[i].Split(':');
            if (thisPArr.Length == 2)
            {
                switch (thisPArr[1].ToLower())
                {
                    case "q":
                        newurl = newurl.Replace("{" + i.ToString() + "}", HttpContext.Current.Request[thisPArr[0]]);
                        break;
                    case "d":
                        if (!string.IsNullOrEmpty(newparam))
                        {
                            newparam += ",";
                        }
                        newparam += thisPArr[0];
                        break;
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(newparam))
                {
                    newparam += ",";
                }
                newparam += thisPArr[0];
            }
        }
        param = newparam.Split(',');
        return newurl;
    }

    public string GetListLinkUrl()
    {
        string[] param = this.ListUrlParameters;
        return SetupLink(this.ListUrl, ref param);
    }

    public void SetGridAddChildLink(GridView grid)
    {
        if (this.ChildDepth > -1)
        {
            HyperLinkField field = new HyperLinkField();
            field.Text = "添加子节点";
            
            string[] param = this.AddUrlParameters;
            string url = SetupLink(this.AddUrl, ref param);
            field.DataNavigateUrlFormatString = url;
            field.DataNavigateUrlFields = param;
            
            //field.DataNavigateUrlFields = this.AddUrlParameters;
            //field.DataNavigateUrlFormatString = this.AddUrl;
            field.HeaderText = "添加节点";
            field.ItemStyle.Width = new Unit(100);
            field.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            field.HeaderStyle.Width = new Unit(100);
            grid.Columns.Add(field);
        }
    }

    public void SetGridEditLink(GridView grid)
    {
        if (this.AllowEdit)
        {
            HyperLinkField field = new HyperLinkField();
            field.Text = "修改";

            string[] param = this.EditUrlParameters;
            string url = SetupLink(this.EditUrl, ref param);
            field.DataNavigateUrlFormatString = url;
            field.DataNavigateUrlFields = param;

            //field.DataNavigateUrlFormatString = this.EditUrl;
            //field.DataNavigateUrlFields = this.EditUrlParameters;
            field.HeaderText = "修改";
            field.ItemStyle.Width = new Unit(40);
            field.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            grid.Columns.Add(field);
        }
    }

    public void SetGridDelLink(GridView grid)
    {
        if (this.AllowDel)
        {
            ConfirmLinkField field = new ConfirmLinkField();
            field.ConfirmText = "确定删除?";
            field.Text = "删除";

            string[] param = this.DeleteUrlParameters;
            string url = SetupLink(this.DeleteUrl, ref param);
            field.DataNavigateUrlFormatString = url;
            field.DataNavigateUrlFields = param;

            //field.DataNavigateUrlFormatString = this.DeleteUrl;
            //field.DataNavigateUrlFields = this.DeleteUrlParameters;
            field.ItemStyle.Width = new Unit(40);
            field.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            field.HeaderText = "删除";
            grid.Columns.Add(field);
        }
    }

    public void SetGridShowLink(GridView grid)
    {
        if (this.AllowShow)
        {
            HyperLinkField field = new HyperLinkField();
            field.Text = "查看";

            string[] param = this.ShowUrlParameters;
            string url = SetupLink(this.ShowUrl, ref param);
            field.DataNavigateUrlFormatString = url;
            field.DataNavigateUrlFields = param;

            //field.DataNavigateUrlFormatString = this.ShowUrl;
            //field.DataNavigateUrlFields = this.ShowUrlParameters;
            field.ItemStyle.Width = new Unit(40);
            field.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            field.HeaderText = "查看";
            grid.Columns.Add(field);
        }
    }

    public void SetUpSearchPanel(Panel panel)
    {
        if ((!string.IsNullOrEmpty(this.ListViewName)) && (!string.IsNullOrEmpty(this.ListViewXmlName)))
        {
            ConfigTable cTab = ConfigTable.GetConfigTable(this.ListViewName, this.ListViewXmlName);
            cTab.SetUpSearchPanel(panel);
            return;
        }
        var list = this.Columns.Where(x => x.IsSearchShow).OrderBy(y=>y.SearchShowOrder);
        foreach (var col in list)
        {
            foreach (Control ctrl in SearchShowFactory.GetSearchTypeField(col.SearchShowType).GetSearchFieldControls(col))
            {
                panel.Controls.Add(ctrl);
            }
        }
    }

    public string GetAddUrl()
    {
        HttpRequest Request = HttpContext.Current.Request;
        string[] param = this.AddUrlParameters;
        string url = this.AddUrl;
        for (int i = 0; i < param.Length; i++)
        {
            string pv = string.Empty;
            if (Request.QueryString[param[i]] != null)
            {
                pv = Request.QueryString[param[i]];
            }
            url = url.Replace("{" + i + "}", pv);
        }

        return url;
    }

    public void SetUpEditPanel(Panel p,string pkValue,bool isEdit)
    {
        DataRow row = null;
        if (isEdit)
        {
            string sql = "select * from " + this.TableName + " where " + this.PkFiledName + "=" + DataTypeFactory.GetSqlValue(pkValue, this[this.PkFiledName].ColumnDataType);
            row = DBFactory.GetConn().exeRow(sql);
        }
        var list = this.Columns.Where(x => x.IsEditShow);
        if (!isEdit)
        {
            list = this.Columns.Where(x => x.IsAddShow && x.EditShowType != EditShowType.Lable);
        }
        list = list.OrderBy(x => x.EditShowOrder);
        foreach (var c in list)
        {
            string value = string.Empty;
            if (isEdit)
            {
                value = row[c.ColumnName].ToString();
            }
            foreach (Control ctrl in EditShowFactory.GetEditShowFieldCreator(c.EditShowType).GetEditFieldControls(c, value, isEdit))
            {
                p.Controls.Add(ctrl);
            }
        }
    }

    public void SetUpShowPanel(Panel p, string pkValue)
    {
        DataRow row = null;        
        {
            string sql = "select * from " + this.TableName + " where " + this.PkFiledName + "=" + DataTypeFactory.GetSqlValue(pkValue, this[this.PkFiledName].ColumnDataType);
            row = DBFactory.GetConn().exeRow(sql);
        }
        var list = this.Columns.Where(x => x.IsEditShow);
        
        list = list.OrderBy(x => x.EditShowOrder);
        foreach (var c in list)
        {
            string value = string.Empty;                        
            value = row[c.ColumnName].ToString();            
            foreach (Control ctrl in EditShowFactory.GetEditShowFieldCreator(EditShowType.Lable).GetEditFieldControls(c, value, true))
            {
                p.Controls.Add(ctrl);
            }
        }
    }

    public string GetInsertSql()
    {
        StringBuilder sb1 = new StringBuilder();
        StringBuilder sb2 = new StringBuilder();
        sb1.Append("insert into ");
        sb1.Append(this.TableName);
        sb1.Append(" ( ");
        sb2.Append(" values (");

        var list = this.Columns.Where(x => x.IsAddShow && x.EditShowType != EditShowType.Lable);
        bool first = true;
        foreach (var c in list)
        {
            if (!first)
            {
                sb1.Append(",");
                sb2.Append(",");
            }
            else
            {
                first = false;
            }
            if (c.EditShowType != EditShowType.Template)
            {
                sb1.Append(c.ColumnName);
                string value = HttpContext.Current.Request[c.ColumnName + "_EditShow"];
                sb2.Append(DataTypeFactory.GetSqlValue(value, c.ColumnDataType));
            }
            else
            {
                
                Page page = HttpContext.Current.Handler as Page;
                if (page != null)
                {
                    Control ctrl = page.LoadControl(c.EditShowTemplatePath);
                    if (ctrl is IEditShowTemplate)
                    {
                        string insertSqlB = ((IEditShowTemplate)ctrl).GetInsertSqlBefore(c);
                        if (string.IsNullOrEmpty(insertSqlB))
                        {
                            sb1.Append(c.EditShowTemplateFields);
                        }
                        else
                        {
                            sb1.Append(insertSqlB);
                        }

                        string templateSql = ((IEditShowTemplate)ctrl).GetInsertSql(c);
                        sb2.Append(templateSql);
                    }
                }                
            }
        }

        if (!string.IsNullOrEmpty(this.OrderFieldName))
        {
            ConfigColumns orderColumn = this[this.OrderFieldName];
            if (orderColumn != null)
            {
                if (!orderColumn.IsAddShow)
                {
                    sb1.Append(",");
                    sb1.Append(this.OrderFieldName);
                    sb2.Append(",");
                    int maxOrder = 0;
                    int.TryParse(DBFactory.GetConn().exe1("select max(" + this.OrderFieldName + ") from " + this.TableName + ""), out maxOrder);
                    sb2.Append(++maxOrder);
                }
            }
        }

        sb1.Append(" ) ");
        sb2.Append(" ) ");
        return sb1.Append(sb2.ToString()).ToString();

    }

    public string GetUpdateSql(string PkValue)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("update ");
        sb.Append(this.TableName);
        sb.Append(" set ");
        var list = this.Columns.Where(x => x.IsEditShow && x.EditShowType != EditShowType.Lable);
        bool first = true;
        foreach (var c in list)
        {
            if (first)
            {
                first = false;
            }
            else
            {
                sb.Append(",");
            }
            if (c.EditShowType != EditShowType.Template)
            {
                sb.Append(c.ColumnName);
                sb.Append("=");
                string value = HttpContext.Current.Request[c.ColumnName + "_EditShow"];
                sb.Append(DataTypeFactory.GetSqlValue(value, c.ColumnDataType));
            }
            else
            {
                Page page = HttpContext.Current.Handler as Page;
                if (page != null)
                {
                    Control ctrl = page.LoadControl(c.EditShowTemplatePath);
                    if (ctrl is IEditShowTemplate)
                    {
                        string templateSql = ((IEditShowTemplate)ctrl).GetUpdateSql(c);
                        sb.Append(templateSql);
                    }
                }
            }
        }
        sb.Append(" where ");
        sb.Append(this.PkFiledName);
        sb.Append("=");
        sb.Append(DataTypeFactory.GetSqlValue(PkValue, this[this.PkFiledName].ColumnDataType));
        return sb.ToString();
    }

    public static ConfigTable GetThisPageConfigTable()
    {
        //获取表名
        string tablename = HttpContext.Current.Request.QueryString["tab"];
        //获取xml名
        string xmlname = HttpContext.Current.Request.QueryString["xml"];
        //从xml文件读取配置
        string path = HttpContext.Current.Server.MapPath("~/configs/tables/" + tablename + "/" + xmlname + ".xml");
        ConfigTable cTab = path.XmlToObj<ConfigTable>();
        return cTab;
    }

    public static ConfigTable GetConfigTable(string tableName, string xmlName)
    {
        string path = HttpContext.Current.Server.MapPath("~/configs/tables/" + tableName + "/" + xmlName + ".xml");
        return path.XmlToObj<ConfigTable>();
    }
}